package com.peng.sort.merge;

import java.util.Arrays;

public class MergeSort {

    public static void main(String[] args) {
        int[] arr = {9, 7, 5, 3, 1, 2};

        mergeSort(arr, 0, arr.length - 1);


        System.out.println(Arrays.toString(arr));
    }

    private static void mergeSort(int[] arr, int L, int R) {
        if (L == R) {
            return;
        }
        int mid = L + ((R - L) >> 1);

        mergeSort(arr, L, mid);
        mergeSort(arr, mid + 1, R);
        merge(arr, L, mid, R);
    }

    private static void merge(int[] arr, int L, int mid, int R) {
        int p1 = L;
        int p2 = mid + 1;
        int[] help = new int[R - L + 1];
        int i = 0;
        while (p1 <= mid && p2 <= R) {
            if (arr[p1] <= arr[p2]) {
                help[i++] = arr[p1++];
            } else {
                help[i++] = arr[p2++];
            }
        }

        while (p1 <= mid) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }


        for (int m = 0; m < help.length; m++) {
            arr[L + m] = help[m];
        }
    }
}
